import React, { Component } from 'react';
import Form from './Form'
import Record from './Record'
import * as RecordAPI from '../api/RecordAPI'

class App extends Component {
  constructor() {
    super()
    this.state = {
      error: null,
      Loading: false,
      records: []
    }
  }

  componentDidMount() {
    // RecordAPI.movie().then(res => {
    //   console.log(JSON.stringify(res))
    // })
    RecordAPI.tableList().then(
      res => this.setState({
        records: res.data,
        Loading: true
      })
    ).catch(
      error => this.setState({
        Loading: true,
        error
      })
    )
  }
  componentWillUnmount = () => {
    this.setState = (state,callback)=>{
      return;
    };
  }
  
  addRecord(record) {
    this.setState({
      // error: null,
      // Loading: true,
      records: [
        ...this.state.records,
        record
      ]
    })
  }

  handleEditRecord(record, data) {
    const recordIndex = this.state.records.indexOf(record);
    const newRecords = this.state.records.map( (item, index) => {
      // console.log(index, recordIndex, item, 222)
      if(index !== recordIndex) {
        return item
      }
      return {
        ...item,
        ...data
      }
    })
    this.setState({
      records: newRecords
    })
  }

  handleDeleteRecord(record) {
    const recordIndex = this.state.records.indexOf(record)
    const newRecords = this.state.records.filter((item, index) => index !== recordIndex )
    this.setState({
      records: newRecords
    })
  }

  render() {
    const { error, Loading, records } = this.state;
    let TableComponent;
    
    if (error) {
      TableComponent = <div>Error: {error.message}</div>
    } else if (!Loading) {
      TableComponent = <div>loading....</div>
    } else {
      TableComponent = (
        <table className="table table-bordered">
          <thead>
            <tr>
              <th scope="col">ID</th>
              <th scope="col">Date</th>
              <th scope="col">Title</th>
              <th scope="col">Amount</th>
              <th scope="col">Actions</th>
            </tr>
          </thead>
          <tbody>
            {records.map((record) => 
              (<Record 
                key={record.id} 
                record={record} 
                handleEditRecord={this.handleEditRecord.bind(this)} 
                handleDeleteRecord={this.handleDeleteRecord.bind(this)}
              />)
            )}
          </tbody>
        </table>
      );
    }
    
    return (
      <React.Fragment>
        <Form handleNewRecord={this.addRecord.bind(this)}/>
        {TableComponent}        
      </React.Fragment>
    )

  }
}

export default App;
